package com.wubi;

import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;

/**
 * a 工 或
 * aa 式 工艺
 * aaa 工
 * hyj	黄毓俊
 * 转 .ini
 * aaem=1,??
 * aaem=2,A股
 * aarm=2,AA制
 * aate=2,A盘
 */
public class TransTest {

	public static final String SOURCE_INI = "C:\\Users\\User\\Desktop\\00pullFirst\\225ini_new.ini";
	public static final String NIUMA_TXT = "C:\\Users\\User\\Desktop\\00pullFirst\\222niuma.txt";
	public static final String DIY_TXT = "C:\\Users\\User\\Desktop\\00pullFirst\\223diy.txt";

	public static void main(String[] args) throws Exception {
		new TransTest().test();
	}

	/**
	 * 1.读.ini
	 * 2.构建map
	 * 3..txt转.ini,map新增数据
	 * 4.写.ini
	 */
	@Transactional
	public void test() {
		try {
			Map<String, LinkedList<String>> map = readIniToConstructMap();

//			readTxtToCompleteMap(map, NIUMA_TXT);
			readTxtToCompleteMap(map, DIY_TXT);

			mapWriteToIni(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void mapWriteToIni(Map<String, LinkedList<String>> map) {
		BufferedWriter bufferedWriter = null;

		try {
			File parentFile = new File(SOURCE_INI).getParentFile();
			String name = new File(SOURCE_INI).getName();
			int i1 = name.lastIndexOf(".");
			String prefix = name.substring(0, i1);
			String subfix = name.substring(i1);
//			File file = new File(parentFile, prefix + "_" + System.currentTimeMillis() + subfix);
			File file = new File(parentFile, prefix + "_new" + subfix);
			//
			File file1 = new File(SOURCE_INI);
			bufferedWriter = new BufferedWriter(new FileWriter(file1));
			//这种遍历,断点性能太慢!!!
//			map.forEach(new BiConsumer<String, LinkedList<String>>() {
//				@SneakyThrows
//				@Override
//				public void accept(String key, LinkedList<String> linkedList) {
//					String temp=key;
//					for (int i = 1; i <= linkedList.size(); i++) {
//						String str = linkedList.get(i - 1);
//						//注意不是\\n\\r,也不是\n\r(相当于先换行再回首,就是内容一行加空一行),而是\r\n(先回首,再换行,就是内容加下一行的"指针")
//						String format = String.format("%s=%d,%s\r\n", key, i, str);
////						bufferedWriter.append(format);
//					}
//
//				}
//			});

			Iterator<Map.Entry<String, LinkedList<String>>> iterator = map.entrySet().iterator();

			while (iterator.hasNext()) {
				Map.Entry<String, LinkedList<String>> entry = iterator.next();
				String key = entry.getKey();
				LinkedList<String> linkedList = entry.getValue();
				for (int i = 1; i <= linkedList.size(); i++) {

					String str = linkedList.get(i - 1);
					//若.ini的map早就包含了该str
					//					if (!


					//注意不是\\n\\r,也不是\n\r(相当于先换行再回首,就是内容一行加空一行),而是\r\n(先回首,再换行,就是内容加下一行的"指针")
					String format = String.format("%s=%d,%s\r\n", key, i, str);
					//					System.out.println(format);
					//todo 文件写到一定程度,内容不再增加,因为BufferedWriter的缓存char的大小!!
					bufferedWriter.append(format);
				}
				bufferedWriter.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedWriter.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static void readTxtToCompleteMap(Map<String, LinkedList<String>> map, String filePath) {
		BufferedReader bufferedReader = null;

		try {
			//读取.txt,补充上面的map
			InputStreamReader fileReader = new InputStreamReader(new FileInputStream(filePath), "UTF-16LE");
			bufferedReader = new BufferedReader(fileReader);
			String line = null;
			//注意,读完一行的时候"指针"就已经跳到下一行首了!!
			line = bufferedReader.readLine();
			//qq五笔的第一行首默认有"看不见"的"空格"符号
			if ('\uFEFF' == line.charAt(0)) {
				line = line.substring(1);
			}

			while (null != line) {

				//空行,跳过.首字符不在[a,y]之间,跳过
				if ("".equals(line) || line.charAt(0) < 'a' || line.charAt(0) > 'y') {
					line = bufferedReader.readLine();
					continue;
				}
				String[] split = line.split(" ");
				String key = split[0];

				LinkedList<String> linkedList;
				if (map.containsKey(key)) {
					linkedList = map.get(key);
					for (int i = 1; i < split.length; i++) {
						if (linkedList.contains(split[i])) {
							continue;
						}
						//读txt的时候只管add
						linkedList.addLast(split[i]);
					}
				} else {
					linkedList = new LinkedList();
					for (int i = 1; i < split.length; i++) {
						linkedList.addLast(split[i]);
					}
					map.put(key, linkedList);
				}

				line = bufferedReader.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static Map<String, LinkedList<String>> readIniToConstructMap() {
		BufferedReader bufferedReaderIni = null;
		Map<String, LinkedList<String>> map = null;

		try {
			//公共,提升
			map = new TreeMap<>();

			//以.ini为蓝本,构建map,要求key自然排序.
			//指定charset,省得改ini文件,一劳永逸
			InputStreamReader fileReader = new InputStreamReader(new FileInputStream(SOURCE_INI), "UTF-16LE");
			bufferedReaderIni = new BufferedReader(fileReader);
			String iniLine = bufferedReaderIni.readLine();
			while (null != iniLine) {

				//空行,跳过.
				if (StringUtils.isBlank(iniLine) || "\uFEFF".equals(iniLine)) {
					iniLine = bufferedReaderIni.readLine();
					continue;
				}
//				System.out.println(iniLine);
				int equalIndex = iniLine.indexOf("=");
				int seperatorIndex = iniLine.indexOf(",");
				String keyStr = iniLine.substring(0, equalIndex);
				//				System.out.println(keyStr);
				String orderStr = iniLine.substring(equalIndex + 1, seperatorIndex);
				String elementStr = iniLine.substring(seperatorIndex + 1);

				LinkedList<String> linkedList = new LinkedList<>();
				if (!map.containsKey(keyStr)) {
					//强制设为0,避免bug,list长度为0时,无法set,会报错
					//					linkedList.set(0, elementStr);
					linkedList.add(elementStr);
					map.put(keyStr, linkedList);

				} else {
					linkedList = map.get(keyStr);
					linkedList.addLast(elementStr);
				}

				iniLine = bufferedReaderIni.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				//写前删除
				new File(SOURCE_INI).delete();
				bufferedReaderIni.close();
//				new File(SOURCE_INI).getName();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
}
